package com.titan.server.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.titan.server.osgi.impl.OSGiWebappLoader;

import edu.ccut.titan.service.ITitanConstants;
import edu.ccut.titan.service.ITitanPropertiesService;
import edu.ccut.titan.service.impl.TitanPropertiesService;

public class BundlesContextListener implements ServletContextListener {

    private static final String OSGI_CONFIG_LOCATION = "osgiConfigLocation";

    private static final String OSGI_CONFIG_LOCATION_DEFAULT = "WEB-INF/config.properties";

    private static final String OSGI_BUNDLES_HOME_LOCATION = "osgiBundlesHomeLocatoin";

    private static final String OSGI_BUNDLES_HOME_LOCATION_DEFAULT = "WEB-INF/bundles";
    
    private static final String WEB_CONTAINER_JSP_CACHE_LOCATION = "webContainerCacheDirectory";

    private OSGiWebappLoader osgiWebappLoader;

    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();

        loadTitanProperties(context);
        
        this.osgiWebappLoader = new OSGiWebappLoader(this.getConfigPropertiesLocation(context), this.getBundlesHomeLocation(context));
        context.setAttribute("osgi", this.osgiWebappLoader);
    }

    public void contextDestroyed(ServletContextEvent event) {
        this.osgiWebappLoader.shutdown();
    }

    private String getConfigPropertiesLocation(ServletContext context) {
        String configPropertiesLocation = context.getInitParameter(OSGI_CONFIG_LOCATION);

        if (configPropertiesLocation == null) {
            configPropertiesLocation = OSGI_CONFIG_LOCATION_DEFAULT;
        }

        return context.getRealPath(configPropertiesLocation);
    }

    private String getBundlesHomeLocation(ServletContext context) {
        String bundlesHomeLocation = context.getInitParameter(OSGI_BUNDLES_HOME_LOCATION);

        if (bundlesHomeLocation == null) {
            bundlesHomeLocation = OSGI_BUNDLES_HOME_LOCATION_DEFAULT;
        }

        return context.getRealPath(bundlesHomeLocation);
    }
    
    private void loadTitanProperties(ServletContext context) {
    	ITitanPropertiesService titanPropertiesService = TitanPropertiesService.getInstance();
    	
    	titanPropertiesService.setProperty(ITitanConstants.TITAN_SERVER_LOCATION, context.getRealPath(""));
    	
    	String cacheLocation = context.getInitParameter(WEB_CONTAINER_JSP_CACHE_LOCATION);
    	if (cacheLocation == null) {
    		throw new RuntimeException("please set jsp cache file for this server");
    	}
    	titanPropertiesService.setProperty(ITitanConstants.TITAN_WEB_CONTAINER_JSP_CACHE_LOCATION, cacheLocation);
    }
}
